<template>
  <div class="action-wrap">
    <el-button v-if="isAction"
               class="first-span"
               type="text"
               @click="visible = true;">{{title}}</el-button>
    <el-dialog :visible="visible"
               :before-close="handleCancel"
               :close-on-click-modal="false"
               title="发票信息"
               width="600px"
               top="15vh"
               append-to-body>
      <el-form ref="ruleForm"
               :model="form"
               :rules="rules"
               label-width="105px">
        <template v-for="(item, index) in formArr">
          <el-form-item :key="index"
                        :label="item.label"
                        :prop="item.props">
            <el-date-picker v-if="item.props === 'invoicingDate'"
                            v-model="form[item.props]"
                            type="date"
                            format="yyyy-MM-dd"
                            style="width: 420px"
                            :disabled="isDisabled === '1'"
                            :placeholder="`请选择${item.label}`">
            </el-date-picker>
            <el-input v-else
                      v-model.trim="form[item.props]"
                      style="width: 420px"
                      :type="item.props === 'desc' ? 'textarea' : 'string'"
                      show-word-limit
                      :placeholder="`请输入${item.label}`"
                      :disabled="isDisabled === '1'"
                      :maxlength="item.maxlength" />
          </el-form-item>
        </template>
        <el-form-item :label="isDisabled === '0'?'上传发票文件':'发票图片'">
          <FileUpload v-if="isDisabled === '0'"
                      :value="invoiceFiles"
                      :limit="isDisabled === '0' ? 6 : invoiceFiles.length"
                      :tip="'附件说明：最多可上传6个附件，附件支持pdf、jpg、png，单个文件不能大于3MB。'"
                      :is-delete="isDisabled === '0'"
                      multiple
                      @input="handleUpload" />
          <Attachments v-else
                       :value="invoiceFiles" />
        </el-form-item>
      </el-form>
      <el-row v-if="isDisabled === '0'">
        <el-col :span="24">
          <div class="footer">
            <el-button type="default"
                       @click="handleCancel">取消</el-button>
            <el-button type="primary"
                       :loading="loading"
                       @click="handleSubmit">确定</el-button>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import FileUpload from "@basic/FileUpload.vue";
import Attachments from "@basic/Attachments.vue";
import _ from 'lodash'
export default {
  name: "FinanceInvoicingAction",
  inject: ["$table"],
  components: { FileUpload, Attachments },
  props: {
    record: {
      type: Object,
      default: () => { }
    },
    url: {
      type: String,
      default: null
    },
    // 按钮名称
    title: String,
    isDisabled: [String, Boolean],
    method: String,
    isAction: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      visible: false,
      loading: false,
      form: {
        invoiceCode: null,
        invoiceMoney: null,
        invoiceNumber: null,
        invoicingDate: null,
        desc: null
      },
      rules: {
        invoicingDate: [{ required: true, message: `请选择开票日期`, trigger: "change" }],
        invoiceNumber: [
          { required: true, message: `请输入发票号码`, trigger: "blur" },
          { pattern: /^[0-9]*$/, message: "请输入发票号码", trigger: ['blur', 'change'] }
        ],
        invoiceMoney: [{ required: true, message: `请输入发票金额`, trigger: "blur" }],
      },
      invoiceFiles: [],
      fileList: []
    }
  },
  computed: {
    formArr () {
      return [
        { label: "开票日期", props: "invoicingDate" },
        { label: "发票代码", props: "invoiceCode", maxlength: 12 },
        { label: "发票号码", props: "invoiceNumber", maxlength: 20 },
        { label: "发票金额", props: "invoiceMoney", maxlength: 20 },
        { label: "发票说明", props: "desc", maxlength: 200 },
      ]
    },
    values () {
      if (this.visible) {
        return this.record
      }
    }
  },
  watch: {
    values: {
      handler (val) {
        if (val?.invoiceFlag) {
          this.form = { ...val.invoice }
          this.invoiceFiles = val.invoice?.invoiceFiles
        }
      }
    },
    immediate: true
  },
  created () {
    if (this.values?.invoiceFlag) {
      this.form = this.values.invoice
      this.invoiceFiles = this.values.invoice?.invoiceFiles
    }
  },
  methods: {
    handleUpload (files) {
      const fileList = files.map((file) => {
        return {
          name: file.name,
          url: file.url
        };
      });
      this.fileList = fileList
    },
    handleSubmit: _.debounce(function () {    // 触发事件
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.submit();
        }
      });
    }, 600),
    async submit () {
      const { code, message } = await axios({
        method: this.method || 'post',
        url: this.url,
        data: {
          billId: this.record.id,
          ...this.form,
          invoiceFiles: this.fileList
        },
      }).catch(err => {
        this.loading = false;
      });
      if (code === 0) {
        this.loading = false;
        this.$message({ type: "success", message });
        this.handleCancel();
        this.$table.search();
      }
    },
    handleCancel () {
      for (let key in this.form) {
        this.form[key] = null;
      }
      this.invoiceFiles = [];
      this.visible = false;
    }
  }
}
</script>

<style scoped>
.action-wrap {
  line-height: 16px !important;
}
.first-span {
  /* border-left: 1px solid var(--prev-border-color-grey);
  border-right: 1px solid var(--prev-border-color-grey); */
  /* padding-left: 6px; */
  /* padding: 0px; */
  border-radius: 0px;
}
</style>